﻿using System;
using System.Collections.Generic;
using System.Threading;
using Yxinmt.Interface;
using Yxinmt.Utility;

namespace Yxinmt.Windows.Meeting
{
    public class CreateFile : BaseWindow, IWindow
    {
        Entity.FileInfo _File { get; set; }
        DocumentViewing _DocumentViewing { get; set; }

        public CreateFile(System.Windows.Window form, IWindow parentForm, System.Windows.Controls.Grid pagePanel, Dictionary<string, object> parameters)
        {
            Window = form;
            ParentWindow = parentForm;
            _PagePanel = pagePanel;
            _Parameters = parameters;
            _DocumentViewing = ParentWindow as DocumentViewing;
            _File = parameters.GetValue<Entity.FileInfo>("File");
            InitSet();

            initView();

            this.SetWindow();

            initLoad();
        }

        static List<CreateFile> _CreateFileList { get; set; }

        static CreateFile()
        {
            _CreateFileList= new List<CreateFile>();
        }

        public static void Dispose()
        {
            _CreateFileList.ForEach(f => f.DisposeFile());
        }

        Dictionary<string, string> _FileNameDict { get; set; }

        void DisposeFile()
        {
            try
            {
                if (_AxFramerControl != null)
                {
                    _AxFramerControl.FramerControl.Close();
                    _AxFramerControl.FramerControl.Dispose();
                    _AxFramerControl.FramerControl = null;
                    _AxFramerControl = null;

                    foreach (var kvp in _FileNameDict)
                    {
                        if (System.IO.File.Exists(kvp.Value)) System.IO.File.Delete(kvp.Value);
                    }
                }
            }
            catch { }
        }

        void initView()
        {
            var webview3 = Utility.Common.GetProperty(_View, "WebView3");
            webview3["Url"] = AppDomain.CurrentDomain.BaseDirectory + "html\\loading.html";
        }

        void initLoad()
        {
            _AxFramerOptions = new Dictionary<string, object>();
            _AxFramerOptions.Add("Name", "AxFramerControl" + Guid.NewGuid().ToString().Replace("-", string.Empty));

            _WindowsFormsHost = (Controls.WindowsFormsHost)this.GetControl("WindowsFormsHost1");

            _AxFramerControl =  new Controls.AxFramerControl(_AxFramerOptions, _WindowsFormsHost);
            _AxFramerControl.InitAxFramerControl(_WindowsFormsHost.WpfWindowsFormsHost);

            _WebView3 = (Controls.WebView2)GetControl("WebView3");
            _WebView3.ReceiveMessage = (msg) =>
            {
                if (msg.GetStringValue("type") == "load") setFileLoad();
            };
        }

        Controls.WebView2 _WebView3 { get; set; }

        public override void ShowLoad()
        {
            base.ShowLoad();

            _AxFramerControl.FramerControl.Activate();
            _AxFramerControl.FramerControl.Refresh();
            _AxFramerControl.FramerControl.Update();
        }

        string GetNewFileName()
        {
            string dir = string.Format("res/MeetingRecord/{0}", _DocumentViewing.MeetingId.ToString().Replace("-", string.Empty));
            return Utility.Common.GetFilePath(dir, _File.FileId.ToString().Replace("-", string.Empty) + ".docx");
        }

        void setFileLoad()
        {
            string fileUrl = _File.FileUrl;
            if (!string.IsNullOrEmpty(fileUrl))
            {
                if (fileUrl.StartsWith("/")) fileUrl = _DocumentViewing.ClientConfig.ServiceUrl + fileUrl;
                fileUrl = Utils.DownloadFile(fileUrl);
            }
            else fileUrl = _File.FilePath;

            InitDocument(fileUrl);

            //this.TaskRun("SaveTask", true, () => SaveTask());
        }

        void SaveTask()
        {
            _SaveTimer = new System.Timers.Timer();
            _SaveTimer.Interval = 1000 * 60;
            _SaveTimer.Elapsed += _SaveTimer_Elapsed;
            _SaveTimer.Start();
        }

        void _SaveTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                Window.Dispatcher.Invoke(() => SaveFile());
            }
            catch (Exception ex)
            {
                LoggerProxy.Exception(Name, "_SaveTimer_Elapsed", ex);
            }
        }

        System.Timers.Timer _SaveTimer { get; set; }

        Controls.WindowsFormsHost _WindowsFormsHost { get; set; }
        Controls.AxFramerControl _AxFramerControl { get; set; }
        Dictionary<string, object> _AxFramerOptions { get; set; }

        string _CurrentFileName { get; set; }

        private void InitDocument(string fileName)
        {
            try
            {
                if (string.IsNullOrEmpty(fileName))
                {
                    fileName = GetNewFileName();
                    CreateWordFile();
                    _AxFramerControl.FramerControl.SaveAs(fileName, "Word.Document");
                }
                else
                {
                    Utils.CopyFile(_FileNameDict, fileName);
                    _AxFramerControl.FramerControl.Open(fileName);
                    _CurrentFileContent = System.IO.File.ReadAllBytes(fileName);
                }

                _CurrentFileName = fileName;
                _AxFramerControl.FramerControl.OnFileCommand += FramerControl_OnFileCommand;
                _IsOpenFile = true;

                _WebView3.SetVisible(false);
            }
            catch (Exception ex)
            {
                _WebView3.SetVisible(false);
                Alert("CreateFile", "InitDocument", ex);
            }
        }

        int _CreateCount { get; set; }

        void CreateWordFile()
        {
            try
            {
                _CreateCount += 1;
                _AxFramerControl.FramerControl.CreateNew("Word.Document");
            }
            catch
            {
                if (_CreateCount < 3)
                {
                    Thread.Sleep(1000);
                    CreateWordFile();
                }
            }
        }

        bool _IsOpenFile { get; set; }

        public override void CloseWindow()
        {
            base.CloseWindow();

            if (_SaveTimer != null)
            {
                _SaveTimer.Stop();
                _SaveTimer.Dispose();
            }

            if (_AxFramerControl != null && _IsOpenFile)
            {
                try
                {
                    SaveFile();
                    _AxFramerControl.FramerControl.Close();
                    _AxFramerControl.FramerControl.Dispose();
                }
                catch (Exception ex)
                {
                    Alert("CreateFile", "CloseWindow", ex);
                }
                _AxFramerControl = null;
            }
        }

        void FramerControl_OnFileCommand(object sender, AxDSOFramer._DFramerCtlEvents_OnFileCommandEvent e)
        {
            switch (e.item)
            {
                case DSOFramer.dsoFileCommandType.dsoFileClose:
                    e.cancel = true;
                    SaveFile();
                    break;
                case DSOFramer.dsoFileCommandType.dsoFileSave:
                    e.cancel = true;
                    SaveFile();
                    break;
                case DSOFramer.dsoFileCommandType.dsoFileSaveAs:
                    e.cancel = true;
                    SaveFile();
                    break;
            }
        }

        byte[] _CurrentFileContent { get; set; }

        public void SaveFile()
        {
            try
            {
                _AxFramerControl.FramerControl.SaveAs(_CurrentFileName, null);
                byte[] bytes = System.IO.File.ReadAllBytes(_CurrentFileName);
                if (bytes == null) return;

                if (Utility.Common.CompareBytes(bytes, _CurrentFileContent))
                {
                    return;
                }

                TaskRun("SaveFile", true, () =>
                {
                    var res2 = RequestService.UploadFile(_File.FileName,string.Empty, string.Empty, bytes);
                    if (!res2.Result)
                    {
                        Alert(res2.Message);
                        return;
                    }

                    Dictionary<string, object> record = new Dictionary<string, object>();
                    record["FileUrl"] = res2.FileUrl;
                    record["FileSize"] = res2.FileSize;
                    record["RecordId"] = _File.FileId;

                    var res = RequestService.SaveRecord(record, true);
                    if (res.Result)
                    {
                        _CurrentFileContent = bytes;
                    }
                    else Alert(res.Message);
                });
            }
            catch (Exception ex)
            {
                Alert("CreateFile", "SaveFile", ex);
            }
        }
    }
}
